package com.lance.answer.question_answer.xj_new;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lance.answer.dto.CompleteInfo;
import com.lance.answer.dto.CourseInfo;
import com.lance.answer.dto.XjCourseVideoInfo;
import com.lance.answer.dto.XjUserCourseInfo;
import com.lance.answer.gui.answer.AnswerObject;
import com.lance.answer.gui.answer.DealJsonString;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.util.Constant;
import com.lance.answer.util.HttpUtil;
import com.lance.answer.util.XinJiangUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.util.CollectionUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

/**
 * @author fengx
 * 新疆一体化答题 按课程答题
 * document.querySelector("video").playbackRate="16"
 */
@Slf4j
public class BatchDoXJAnswerTask  extends Thread{

    private String driverPath;
    private LinkedBlockingDeque<CourseInfo> userCourses;

    public BatchDoXJAnswerTask(String driverPath, LinkedBlockingDeque<CourseInfo> userCourses) {
        this.driverPath = driverPath;
        this.userCourses = userCourses;
    }


    @SneakyThrows
    @Override
    public void run() {

        while (userCourses.size() > 0) {

            System.err.println("hello world");

            CourseInfo courseInfo = userCourses.take();
            String userName = courseInfo.getUser();
            String password = courseInfo.getPwd();
            String subjectName = courseInfo.getSubjectName();
            int openCourseId = courseInfo.getOpenCourseId();
            Map<String, AnswerObject> answerMap = courseInfo.getAnswerMap();
            log.info("任务：{} 剩余 {} 行，当前课程：{} 用户名：{} 密码：{}",
                    Thread.currentThread().getName(),userCourses.size(),subjectName,userName, password);
            study(subjectName, openCourseId,courseInfo.getXjCourseVideoInfo(), answerMap, userName, password,courseInfo.isEqulas());
            //log.info("{} 开始执行刷题任务",Thread.currentThread().getName());

        }

        if (userCourses.size() == 0) {
            log.info("课程所有用户均已执行完毕，系统将在20min后结束");
            TimeUnit.MINUTES.sleep(20);
            return;
        }
    }


    public static void study(String majorName, int openCourseId,
                             XjCourseVideoInfo courseInfo, Map<String, AnswerObject> answerMap, String username, String pwd, boolean equlas) throws IOException {

        boolean isComplete = false;
        try{

            File directory = new File("E:\\answerInfo一体化\\"+majorName);
            if(!directory.exists()){
                directory.mkdirs();
            }

            String filePath = "E:\\answerInfo一体化\\"+majorName+"\\"+username+"-study.txt";
            File userCompleteInfoFile = new File(filePath);
            InputStream inputStream = new FileInputStream(userCompleteInfoFile);
            String completeInfoStr = IOUtils.toString(inputStream,"UTF-8");
            List<CompleteInfo> completeInfoList = JSONObject.parseArray(completeInfoStr, CompleteInfo.class);
            if(null!=completeInfoList){
                for(CompleteInfo info:completeInfoList){
                    if ("没有这门课程！".equals(info.getSummary())||"完成了这门课程！".equals(info.getSummary())) {
                        isComplete = true;
                        break;
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        if(isComplete){
            return;
        }



        WebDriver driver = Util.getDriver("c:\\ynouAutoStudy\\chromedriver.exe");
        try {
            driver.get("https://xjskk.open.com.cn/stuspace-auth/#/login");
            XinJiangUtil.studentLogin(driver, username, pwd);
            Thread.sleep(4000);
            // FIXME 有的人报了多个专业
           try{
               for (WebElement we : findWeElements(driver, "div[class='part']", 20)) {
                   System.err.println("we.getAttribute(\"title\")):" + we.getAttribute("title"));
                   if (majorName.equals(we.getAttribute("title"))) {
                       we.click();
                       break;
                   }
                   // FIXME 正式要删掉
                   if (!Strings.isNullOrEmpty(we.getAttribute("title")) && we.getAttribute("title").contains("2022年春季")) {
                       we.click();
                       break;
                   }
                   if (!Strings.isNullOrEmpty(we.getAttribute("title")) && we.getAttribute("title").contains("2022春季")) {
                       we.click();
                       break;
                   }
                   if (!Strings.isNullOrEmpty(we.getAttribute("title")) && we.getAttribute("title").contains("2021年秋季")) {
                       we.click();
                       break;
                   }
                   if (!Strings.isNullOrEmpty(we.getAttribute("title")) && we.getAttribute("title").contains("2021年春季")) {
                       we.click();
                       break;
                   }
                   if (!Strings.isNullOrEmpty(we.getAttribute("title")) && we.getAttribute("title").contains("2021秋季")) {
                       we.click();
                       break;
                   }
                   if (!Strings.isNullOrEmpty(we.getAttribute("title")) && we.getAttribute("title").contains("2021春季")) {
                       we.click();
                       break;
                   }
                   if (!Strings.isNullOrEmpty(we.getAttribute("title")) && we.getAttribute("title").contains("2020年秋季")) {
                       we.click();
                       break;
                   }
                   if (!Strings.isNullOrEmpty(we.getAttribute("title")) && we.getAttribute("title").contains("2020年春季")) {
                       we.click();
                       break;
                   }
                   if (!Strings.isNullOrEmpty(we.getAttribute("title")) && we.getAttribute("title").contains("2020秋季")) {
                       we.click();
                       break;
                   }
                   if (!Strings.isNullOrEmpty(we.getAttribute("title")) && we.getAttribute("title").contains("2020春季")) {
                       we.click();
                       break;
                   }
                   if (!Strings.isNullOrEmpty(we.getAttribute("title")) && we.getAttribute("title").contains("2019年秋季")) {
                       we.click();
                       break;
                   }
                   if (!Strings.isNullOrEmpty(we.getAttribute("title")) && we.getAttribute("title").contains("2019年春季")) {
                       we.click();
                       break;
                   }
                   if (!Strings.isNullOrEmpty(we.getAttribute("title")) && we.getAttribute("title").contains("2019年季")) {
                       we.click();
                       break;
                   }
                   if (!Strings.isNullOrEmpty(we.getAttribute("title")) && we.getAttribute("title").contains("2019年季")) {
                       we.click();
                       break;
                   }
                   // FIXME 正式要删掉
               }
           }catch (Exception e1){

           }

            Thread.sleep(5000);
            Set<Cookie> cookies = driver.manage().getCookies();
            String studentSpaceProfile = Util.getStudentSpaceProfile2(cookies);
            String authorization = Util.getAuthorization2(cookies);
            Map<String, String> heads = Maps.newHashMap();
            String cookie = Util.getCookie(cookies);
            initHeads(heads, studentSpaceProfile, authorization);

            // 获取SID
            int sid = getSid(openCourseId, cookie, heads);



            // SID=0说明没有这门课
            if(sid ==0){
                try {
                    List<CompleteInfo> completeInfoList = Lists.newArrayList();
                            CompleteInfo info = new CompleteInfo();
                    info.setSummary("没有这门课程！");
                    completeInfoList.add(info);
                    String filePath = "E:\\answerInfo一体化\\" + majorName;
                    filePath = filePath + "\\" + username + "-study.txt";
                    File completeInfoFile = new File(filePath);
//                    if (!completeInfoFile.exists()) {
//                        completeInfoFile.c();
//                    }
                    FileUtils.write(completeInfoFile, JSONObject.toJSONString(completeInfoList, SerializerFeature.PrettyFormat), "utf-8");
                    driver.close();
                    driver.quit();
                }catch (Exception e){
                    e.printStackTrace();
                }
                return;
            }

            driver.get("https://xjskk.open.com.cn/stuspace/#/course?oId=" + openCourseId + "&sId=" + sid);

            Util.switchToLast(driver);
            Thread.sleep(8000);
            // countCompleteNums:22 说明就从22开始：
            int countCompleteNums = countCompleteNums(driver,equlas);
            System.err.println("countCompleteNums:" + countCompleteNums);

            if(openCourseId==37532&&countCompleteNums==28){
                countCompleteNums=30;
            }
            if(openCourseId==38829&&countCompleteNums==28){
                countCompleteNums=30;
            }

            List<XjCourseVideoInfo.ContentDTO> contentDTOList = courseInfo.getContent();
            int courseInfoSize = contentDTOList.size();
            System.err.println("courseInfoSize:" + courseInfoSize);

            if((countCompleteNums == courseInfoSize)){

                List<CompleteInfo> completeInfoList = Lists.newArrayList();

                CompleteInfo info = new CompleteInfo();
                info.setSummary("完成了这门课程！");
                completeInfoList.add(info);

                FileUtils.write(new File("E:\\answerInfo一体化\\"+majorName+"\\"+username+"-study.txt"),
                        JSONObject.toJSONString(completeInfoList, SerializerFeature.PrettyFormat), "utf-8");
                // 完成了！
                return;

            }



            System.err.println("继续答题" + "countCompleteNums:" + countCompleteNums + "\t courseInfoSize:" + courseInfoSize + "   user:" + username);

            //   Thread.sleep(5000000);

            String watchVideoUrl = driver.getCurrentUrl();

            // fixme todo 10-28可以增加一个判断机制：先加载已经完成的课程，然后把已经完成的课程事项放在一个集合里，最后遍历的时候再比较
            //      for (XjCourseVideoInfo.ContentDTO content : courseInfo.getContent()) {
      //      for (int i = countCompleteNums; i < courseInfoSize; i++) {
            for (int i = countCompleteNums; i < courseInfoSize; i++) {
      //      for (int i = 0; i < courseInfoSize; i++) {
                XjCourseVideoInfo.ContentDTO content = contentDTOList.get(i);
                boolean isGoOn = true;
                // 先看视频
                for (XjCourseVideoInfo.ContentDTO.ResourcesDTO resources : content.getResources()) {

                    System.err.println(":resources:"+resources);

                    //   final Semaphore lock = new Semaphore(1);
                    // 17：52
                    driver.navigate().refresh();
                    Thread.sleep(4000);
                    // 17：52

                    int retry = 0;
                    try {
                        retry++;

                        boolean isFind = false;
                        while (!isFind) {
                           // if (i > 11) {
                            if (i > 10) {
                                ((JavascriptExecutor) driver).executeScript("window.scrollTo(0,2000)");
                            }
                            if (i > 20) {
                                ((JavascriptExecutor) driver).executeScript("window.scrollTo(0,3500)");
                            }
                            //一、 保存视频信息
                         //   saveVideoInfo(openCourseId, resources, cookie, heads);
                            saveVideoInfo(openCourseId, resources, cookie, heads,retry);
                            // FIXME 二、学完之后必须点击一下：

                            Thread.sleep(2000);
//                            String watchVideoUrl = initWatchVideoString(openCourseId, sid, resources);
//                            driver.get(watchVideoUrl);
                            if (clickVideo(driver, watchVideoUrl)) {
                                Thread.sleep(3000 + retry * 10000);
                                driver.navigate().back();
                            }

                            // 如果没有考试得话就继续当前循环
                            if (content.getExamines().size() < 1) {
                                isGoOn = false;
                                break;
                            }
                            Thread.sleep(2000);
                            driver.navigate().refresh();
                            if (i > 10) {
                                ((JavascriptExecutor) driver).executeScript("window.scrollTo(0,2000)");
                            }
                            if (i > 20) {
                                ((JavascriptExecutor) driver).executeScript("window.scrollTo(0,3500)");
                            }
                            // 这里睡眠很关键，等待页面加载
                            Thread.sleep(6000);
                          //  Thread.sleep(3000);
                            // FIXME 开始做题
                            System.err.println("开始做题.....");
                            XjCourseVideoInfo.ContentDTO.ExaminesDTO examines = content.getExamines().get(0);
                            System.err.println("examines:" + examines);
                            // 异常说明答题次数达到了最大次数
                            // 1、点击答题
                            // FIXME 2021-10-27 增加试错机制，在这里判断是否可以点击当前页面的答题，如果在有答题的情况下不能正常答题就继续循环看视频
                            isFind = clickAnswer(driver,watchVideoUrl, equlas);
                           // if (i > 11) {
                            if (i > 10) {
                                ((JavascriptExecutor) driver).executeScript("window.scrollTo(0,2000)");
                            }
                            if (i > 20) {
                                ((JavascriptExecutor) driver).executeScript("window.scrollTo(0,3500)");
                            }
                            // 如果重试次数大于10次，就抛出异常
                        //    if (retry > 10) {
                            if (retry > 3) {
                                throw new Exception("用户:XXXX" + "出错了");
                            }
                        }
                        if (!isGoOn) {
                            continue;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        // 12-7
                        break;
                        // 12-7
                    }

                    // 正式开始答题
                    try {
                        Thread.sleep(3000);
                        // 2、确定答题
                        confirmAnswer(driver);
                        Thread.sleep(3000);
                        // 3、开始答题 TODO list-children-class children-div-top
                        List<WebElement> questionWeList = findWeElements(driver, "div[class^='list-children-class']", 20);
                        doAnswer(questionWeList, answerMap);
                        // 4、提交测验
                        Thread.sleep(2000);
                        btnClick(driver, "提交测验");
                        Thread.sleep(3000);
                        btnClick(driver, "确定");
                        Thread.sleep(2000);
                        // 答题完成后返回课程目录
                        btnClick(driver, "返回课程目录");

                    } catch (Exception e) {
                        e.printStackTrace();
                        System.err.println("continue");
                        //   continue;
                    }
                    Thread.sleep(2000);
                }

            }

        } catch (Exception e) {
            File file = new File("d:\\user-" + majorName + "-error.txt");
            FileOutputStream outputStream = new FileOutputStream(file, true);
            String s = username + "," + pwd + "\r\n";
            outputStream.write(s.getBytes());
            e.printStackTrace();

        } finally {
            try {
                driver.close();
                driver.quit();
            } catch (Exception e) {

            }
        }
    }


    public static int countCompleteNums(WebDriver driver,boolean equals) {

        int completeSize = 0 ;
        if(!equals){
            completeSize = 1;
        }
        List<WebElement> list = findWeElements(driver, "span[class^='totalScore ']", 30);
        for(WebElement  webElement:list){
            String text =webElement .getText();
            String REGEX = "[^(0-9)]";
            text = Pattern.compile(REGEX).matcher(text).replaceAll("").trim();
            System.err.println("text:" + text);
            if (!Strings.isNullOrEmpty(text) && Integer.parseInt(text) >= 0) {
                 completeSize++;
            }
        }
        if(completeSize == 1&!equals){
            return 0;
        }else {
            return completeSize;
        }

    }



    public static void btnClick(WebDriver driver, String btnName) {
        for (WebElement confirmBtn : driver.findElements(By.cssSelector("button[type='button']"))) {
            if (confirmBtn.getText().equals(btnName)) {
                confirmBtn.click();
                break;
            }
        }
    }

    public static void saveVideoInfo(int openCourseId, XjCourseVideoInfo.ContentDTO.ResourcesDTO resources,
                                     String cookie, Map<String, String> heads) throws Exception {
       saveVideoInfo(openCourseId,resources,cookie,heads,0);
    }

    public static void saveVideoInfo(int openCourseId, XjCourseVideoInfo.ContentDTO.ResourcesDTO resources,
                                     String cookie, Map<String, String> heads,int retry) throws Exception {
        String saveUrl = "https://xjskk.open.com.cn/api/student/student-space-service/resources/saveResourceTrace";
        JSONObject saveJson = initSaveJson(openCourseId, resources);
        String saveString = HttpUtil.postJson(saveUrl, saveJson, cookie, heads);

        System.err.println("saveString:"+saveString);

        if(saveString.contains("请按照顺序学习")){
            return;
        }

        int contentId = (int) JSON.parseObject(saveString).get("content");
        Thread.sleep(5 * 1000);
        // 更新观看时间
        String updateUrl = "https://xjskk.open.com.cn/api/student/student-space-service/resources/updateResourceTrace";
        int traceTime = 0;
         int step = 600;
       //  int step = 180000;
        int totalTime = resources.getTraceTime();
        while (traceTime<totalTime){
            traceTime +=step;
            if(traceTime>totalTime){
                traceTime = totalTime;
             //   traceTime = totalTime+1;
               // traceTime = totalTime+retry;
                // fixme 强行+1
                //   traceTime = totalTime+1;
            }
            // JSONObject updateJson = initUpdateJson(openCourseId, contentId, resources);
            JSONObject updateJson = initUpdateJson(openCourseId, contentId,resources.getResourceUid(),totalTime,traceTime);
            System.out.println("HttpUtil.postJson(updateUrl, updateJson, cookie, heads):"+HttpUtil.postJson(updateUrl, updateJson, cookie, heads));
            HttpUtil.postJson(updateUrl, updateJson, cookie, heads);
            Thread.sleep(2*1000);
        }
    }



    private static void doAnswer(List<WebElement> questionWeList, Map<String, AnswerObject> answerMap) {
        for (WebElement questionWe : questionWeList) {

            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            WebElement titleWe = questionWe.findElement(By.className("children-value-class"));
            // fixme
            String title = titleWe.getText();
            title = Util.dealContent(title);
            title = DealJsonString.delHTMLTag(title);
            AnswerObject answerObject = answerMap.get(title);
            if (answerObject == null) {
                System.err.println("答案不存在:" + title);
                // FIXME 如果问题不存在，就用HANLP来匹配
                double similarity = 0.0;
                String answerTitle = "";
                for (Map.Entry<String, AnswerObject> entry : answerMap.entrySet()) {
                    double k1 = DealJsonString.getSimilarity(title, entry.getKey());
                    if (k1 > similarity) {
                        similarity = k1;
                        answerTitle = entry.getKey();
                    }
                }
                // 相似度为0.9 就选择
                if (similarity > 0.80) {
                    answerObject = answerMap.get(answerTitle);
                } else {
                    try {
                    //    System.err.println("==答案真的不存在===");
                     //   Thread.sleep(20000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
           if(null == answerObject){
               continue;
           }
           try {
               // FIXME TODO有时候答题错误？？？？？？
               doChoiceExercise(questionWe, answerObject.getAnswers());
           }catch (Exception e){
               e.printStackTrace();
           }
        }
    }

    private static void doChoiceExercise(WebElement answerElement, List<String> realAnswers) {

//        try{
//            Random random = new Random();
//            // 6%的几率任意选
//            if(random.nextInt(100)<6){
//                answerElement.findElements(By.cssSelector("div[class='clearfix']")).get(0)
//                        .findElement(By.cssSelector("span[class^='el-']")).click();
//                return;
//            }
//        }catch (Exception e){
//            e.printStackTrace();
//        }

        // 遍历题目的每一个选项
        for (WebElement singleAnswerElement : answerElement.findElements(By.cssSelector("div[class='clearfix']"))) {
            String answerContent = singleAnswerElement.
                    findElement(By.cssSelector("span[class='option-value-class']")).getText();
            answerContent = Util.dealContent(answerContent);
            // 找到单选框或复选框
            // el-checkbox el-radio
            WebElement labelElement = singleAnswerElement.findElement(By.cssSelector("label[class^='el-']"));

            // 找到真正的点击按钮 el-radio__input el-checkbox__input
            WebElement realClickElement = singleAnswerElement.findElement(By.cssSelector("span[class^='el-']"));

            String labelClass = labelElement.getAttribute("class");

            // 单选或者判断题
            WebElement clickWebElement = null;
            if (labelClass.contains("radio")) {
                clickWebElement = labelElement.findElement(By.cssSelector("input[type='radio']"));
            }
            if (labelClass.contains("checkbox")) {
                clickWebElement = labelElement.findElement(By.cssSelector("input[type='checkbox']"));
            }
            // FIXME 判断题0：对 1：错
            // 这里的ID是每个选项的ID answerContent是每个选项的内容
            for (String realAnswer : realAnswers) {
                if (DealJsonString.delHTMLTag(answerContent).equals(DealJsonString.delHTMLTag(realAnswer))) {
                    assert clickWebElement != null;
                    if (!clickWebElement.isSelected()) {
                        realClickElement.click();
                    }
                }
            }


        }
    }

    public static int getSid(int openCourseId, String cookie, Map<String, String> heads) throws IOException {

        int sid = 0;
        String getCourseInfoUrl = "https://xjskk.open.com.cn/api/student/student-space-service/courses/" +
                "getStudentCourses?pageNumber=1&pageSize=2000000&status=1&courseNameCode=";
        XjUserCourseInfo userCourseInfo = JSON.parseObject(HttpUtil.get(getCourseInfoUrl, cookie, heads),
                XjUserCourseInfo.class);
        // 获取每个人每门课程独有的SID
        for (XjUserCourseInfo.ContentDTO.ItemsDTO items : userCourseInfo.getContent().getItems()) {
            if (openCourseId == items.getOpenCourseId()) {
                sid = items.getSelectCourseId();
                break;
            }
        }
        return sid;
    }


    public static void initHeads(Map<String, String> heads, String studentSpaceProfile, String authorization) {
        heads.put("referer", "https://xjskk.open.com.cn/stuspace/");
        heads.put("authority", "xjskk.open.com.cn");
        heads.put("path", "/api/student/student-space-service/resources/updateResourceTrace");
        heads.put("scheme", "scheme");
        heads.put("open-student-space-profile", studentSpaceProfile);
        heads.put("origin", "https://xjskk.open.com.cn");
        heads.put("authorization", authorization);
    }

    public static JSONObject initSaveJson(int openCourseId, XjCourseVideoInfo.ContentDTO.ResourcesDTO resources) {
        JSONObject saveJson = new JSONObject();
        // 课程ID，固定的
        saveJson.put("openCourseId", openCourseId);
        // 单个视频的资源ID
        saveJson.put("resourceUid", resources.getResourceUid());
        // 视频总时长
        saveJson.put("totalTime", resources.getTraceTime());
        saveJson.put("traceTime", 0);
        return saveJson;
    }

    public static JSONObject initUpdateJson(int openCourseId, int contentId, String resourceUid,int totalTime,int traceTime) {
        /**
         * {
         *   "openCourseId": 33960,
         *   "resourceUid": "40659eb3-91a4-4b53-b051-f6fe07afa16a",
         *   "traceTime": 138,
         *   "totalTime": 795,
         *   "id": 21520262
         * }
         */
        JSONObject updateJson = new JSONObject();
        updateJson.put("openCourseId", openCourseId);
        updateJson.put("resourceUid", resourceUid);
        updateJson.put("traceTime", traceTime);
        // 系统更新加了一个totalTime
        updateJson.put("totalTime", totalTime);
        // 课程的ID
        updateJson.put("id", contentId);
        return updateJson;
    }


    public static JSONObject initUpdateJson(int openCourseId, int contentId, XjCourseVideoInfo.ContentDTO.ResourcesDTO resources) {
        JSONObject updateJson = new JSONObject();
        updateJson.put("openCourseId", openCourseId);
        updateJson.put("resourceUid", resources.getResourceUid());
        updateJson.put("traceTime", resources.getTraceTime());
        // 课程的ID
        updateJson.put("id", contentId);
        return updateJson;
    }


//    public static boolean clickVideo(WebDriver driver, XjCourseVideoInfo.ContentDTO.ResourcesDTO resources) {
//        boolean isFind = false;
//        for (WebElement span : findWeElements(driver, "span[class='resourceName font-blue']", 30)) {
//            if (DealJsonString.delHTMLTag(span.getText()).equals(DealJsonString.delHTMLTag(resources.getName()))) {
//                // 点击完成之后要break
//                span.click();
//                isFind = true;
//                break;
//            }
//        }
//        return isFind;
//    }

    public static boolean clickVideo(WebDriver driver, String watchVideoUrl) {

//        boolean isSuccess = false;
//
//        while (!isSuccess){
//            try{
//                List<WebElement> resourceList = findWeElements(driver, "span[class='resourceName font-blue']", 30);
//                if (resourceList.size() < 1) {
//                    return false;
//                }
//                resourceList.get(resourceList.size() - 1).click();
//                return true;
//            }catch (Exception e){
//                driver.get(watchVideoUrl);
//                try {
//                    Thread.sleep(5000);
//                } catch (InterruptedException e11) {
//                    e11.printStackTrace();
//                }
//            }
//
//        }
//        return true;

            try{
                List<WebElement> resourceList = findWeElements(driver, "span[class='resourceName font-blue']", 30);
                if (resourceList.size() < 1) {
                    return false;
                }
                resourceList.get(resourceList.size() - 1).click();
                return true;
            }catch (Exception e){
                driver.get(watchVideoUrl);
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e11) {
                    e11.printStackTrace();
                }
                return false;
            }

    }


//    public static boolean clickAnswer(WebDriver driver, XjCourseVideoInfo.ContentDTO.ExaminesDTO examines) {
//        // fixme 按理说应该只选择最后一个答题
//        boolean isFind = false;
//        for (WebElement span : findWeElements(driver, "span[class='testName font-blue']", 30)) {
//            if (DealJsonString.delHTMLTag(span.getText()).equals(DealJsonString.delHTMLTag(examines.getName()))) {
//                // 点击完成之后要break
//                span.click();
//                isFind = true;
//                break;
//            }
//        }
//        return isFind;
//    }

//    public static boolean clickAnswer(WebDriver driver, XjCourseVideoInfo.ContentDTO.ExaminesDTO examines) {
//        // fixme 按理说应该只选择最后一个答题
//        List<WebElement> testList = findWeElements(driver, "span[class='testName font-blue']", 30);
//        List<WebElement> resourceList = findWeElements(driver, "span[class='resourceName font-blue']", 30);
//
//        // 正常情况   testList的个数为0 也不成功
//        if(testList.size()==0){
//            return false;
//        }
//        // 正常情况  resourceList的个数 = testList的个数+1
//        if(testList.size()+1!=resourceList.size()){
//            return false;
//        }
//        testList.get(testList.size()-1).click();
//        return true;
//    }


    public static boolean clickAnswer(WebDriver driver,String watchVideoUrl, boolean equals) {

        driver.get(watchVideoUrl);
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
      try {
          // fixme 按理说应该只选择最后一个答题
          List<WebElement> testList = findWeElements(driver, "span[class='testName font-blue']", 30);
          List<WebElement> resourceList = findWeElements(driver, "span[class='resourceName font-blue']", 30);
          System.err.println("testList:::"+testList.size());
          System.err.println("resourceList:::"+resourceList.size());

          // 正常情况   testList的个数为0 也不成功
          if (!equals && testList.size() == 0) {
              return false;
          }
          // 正常情况  resourceList的个数 = testList的个数+1
          if (!equals && testList.size() + 1 != resourceList.size()) {
              return false;
          }

          // add 2022-05-22
          // 正常情况  resourceList的个数 = testList的个数
//        if (equals && testList.size() != resourceList.size()) {
//            return false;
//        }
          // add 2022-05-22

          System.err.println("testList1111:::"+testList.size());
          testList.get(testList.size() - 1).click();
          return true;
      }catch (Exception e){
          e.printStackTrace();
          driver.get(watchVideoUrl);
          try {
              Thread.sleep(2000);
          } catch (InterruptedException ex) {
              ex.printStackTrace();
          }
          return false;
      }
    }

    public static void confirmAnswer(WebDriver driver) {
        List<WebElement> saveButtons = findWeElements(driver, "button[type='button']", 30);
        if (!CollectionUtils.isEmpty(saveButtons)) {
            for (WebElement webElement : saveButtons) {
                String text = webElement.getText();
                if (text.contains("确 定")) {
                    webElement.click();
                    break;
                }
            }
        }
    }

    private static List<WebElement> findWeElements(WebDriver driver, String cssSelector, int second) {
        return (new WebDriverWait(driver, Duration.ofSeconds(second))).until((ExpectedCondition<List<WebElement>>)
                d -> {
                    assert d != null;
                    return d.findElements(By.cssSelector(cssSelector));
                });
    }


}
